package com.luhuiguo.cms.server.handler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import com.luhuiguo.cms.server.entity.Article;
import com.luhuiguo.cms.server.service.ArticleService;
import com.luhuiguo.cms.server.util.MapperUtils;
import com.luhuiguo.cms.shared.model.ArticleListModel;
import com.luhuiguo.cms.shared.rpc.LoadArticles;
import com.luhuiguo.cms.shared.rpc.LoadArticlesResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;

@Component
public class LoadArticlesHandler implements ActionHandler<LoadArticles, LoadArticlesResult> {


    @Autowired
    private ArticleService articleService;

    @PreAuthorize("isAuthenticated()")
    @Override
    public LoadArticlesResult execute(LoadArticles action, ExecutionContext context) throws ActionException {

        List<Article> list;
        int count = 0;
        if (action.getStatus() < 0) {

            list = articleService.findArticlesByStatus(action.getStatus(), action.getStart(), action.getLimit());
            count = articleService.getArticleCountByStatus(action.getStatus());
        } else {

            list = articleService.findArticlesByChannelId(action.getChannelId(), action.getStart(), action.getLimit());
            count = articleService.getArticleCountByChannelId(action.getChannelId());
        }
        return new LoadArticlesResult(MapperUtils.mapList(list, ArticleListModel.class), action.getStart(), action
                .getLimit(), count);
    }

    @Override
    public Class<LoadArticles> getActionType() {
        return LoadArticles.class;
    }

    @Override
    public void rollback(LoadArticles action, LoadArticlesResult result, ExecutionContext context)
            throws ActionException {

    }

}
